﻿using System;
using System.Data;
using System.Data.SqlClient;
using System.Collections;

namespace Coogle.DataAccess
{
    public class DbGateway
    {
        private readonly String connectionString;

        public DbGateway(String connectionString)
        {
            this.connectionString = connectionString;
        }

        public TResult FindSingle<TResult>(IFindOneQuery<TResult> query)
        {
            DataRow row;
            using (var connection = new SqlConnection(connectionString))
            using (var command = query.CreateCommand(connection))
            {
                connection.Open();
                using (var reader = command.ExecuteReader())
                {
                    var table = GetDataTable(reader);
                    row = IsEmpty(table.Rows) ? null : table.Rows[0];
                }
            }
            return query.Map(row);
        }

        public TResult Find<TResult>(IFindQuery<TResult> query) where TResult : IEnumerable
        {
            DataTable table;
            using (var connection = new SqlConnection(connectionString))
            using (var command = query.CreateCommand(connection))
            {
                connection.Open();
                using (var reader = command.ExecuteReader())
                {
                    table = GetDataTable(reader);
                }
            }
            return query.Map(table);
        }

        private static DataTable GetDataTable(SqlDataReader reader)
        {
            var table = new DataTable();
            table.Load(reader);
            return table;
        }

        private static bool IsEmpty(DataRowCollection rows)
        {
            return rows.Count == 0;
        }
    }
}
